/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "can.h"
#include "dma.h"
#include "i2c.h"
#include "spi.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bmp280Driver.h"
#include "can_comm.h"
#include "mux.h"
#include "bsp_dwt.h"
#include "BMI088driver.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

uint8_t broken_sensors[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint8_t float_to_uint8(float x)
{
  // 定义映射参数
  const float lower_bound = 30000.0f;
  const float upper_bound = 110000.0f;
  const float split_point = 100000.0f;
  const uint8_t split_value = 198;

  // 边界处理
  if (x <= lower_bound)
    return 0;
  if (x >= upper_bound)
    return 255;

  // 低精度区间映射 [30000, 100000] => [0, 198]
  if (x <= split_point)
  {
    float ratio = (x - lower_bound) / (split_point - lower_bound);
    return (uint8_t)(ratio * split_value + 0.5f); // 四舍五入
  }
  // 高精度区间映射 [100000, 110000] => [198, 255]
  else
  {
    float ratio = (x - split_point) / (upper_bound - split_point);
    return split_value + (uint8_t)(ratio * (255 - split_value) + 0.5f);
  }
}
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
static CANCommInstance *can_comm_instance; // CAN通信实例数组

#ifdef FINGER_UP

static BMP280DriverInstance_s *bmp280_instance[20]; // 设备实例数组
static BMP280_measure_s *bmp280_measure[20];        // 测量值数组
#pragma pack(1)
typedef struct
{
  uint8_t pressure[20]; // 气压值
} Cancomm_send_s;
#pragma pack()
typedef struct
{
  uint8_t header; // 帧头
} Cancomm_recv_s;
static Cancomm_send_s cancomm_send_data;  // CAN通信发送数据结构体
static Cancomm_recv_s *cancomm_recv_data; // CAN通信接收数据结构体

#endif

#if defined FINGER_MID || defined FINGER_DOWN

static BMP280DriverInstance_s *bmp280_instance[16]; // 设备实例数组
static BMP280_measure_s *bmp280_measure[16];        // 测量值数组
#pragma pack(1)
typedef struct
{
  uint8_t pressure[16]; // 气压值
} Cancomm_send_s;
#pragma pack()
typedef struct
{
  uint8_t header; // 帧头
} Cancomm_recv_s;
static Cancomm_send_s cancomm_send_data;  // CAN通信发送数据结构体
static Cancomm_recv_s *cancomm_recv_data; // CAN通信接收数据结构体

#endif

#ifdef PALM
static BMP280DriverInstance_s *bmp280_instance[60]; // 设备实例数组
static BMP280_measure_s *bmp280_measure[60];        // 测量值数组

#pragma pack(1)
typedef struct
{
  float pressure[60]; // 气压值
} Cancomm_send_s;
#pragma pack()
typedef struct
{
  uint8_t header; // 帧头
} Cancomm_recv_s;
static Cancomm_send_s cancomm_send_data;  // CAN通信发送数据结构体
static Cancomm_recv_s *cancomm_recv_data; // CAN通信接收数据结构体

#endif

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_CAN_Init();
  MX_I2C1_Init();
  MX_SPI1_Init();
  /* USER CODE BEGIN 2 */
  DWT_Init(72); // 初始化DWT计时器
  uint8_t flag = BMI088Init(&hspi1, 1); // 初始化BMI088
#ifdef FINGER_UP
  CANComm_Init_Config_s cancomm_conf = {
      .can_config = {
          .can_handle = &hcan,
          .rx_id = 0x101,
          .tx_id = 0x102,
      },
      .send_data_len = sizeof(Cancomm_send_s),
      .recv_data_len = sizeof(Cancomm_recv_s),
  };
  can_comm_instance = CANCommInit(&cancomm_conf); // 初始化CAN通信实例

  BMP280Driver_conf_s bmp280_conf = {
      .iic_conf = {
          .dev_address = BMP280_ADDRESS,
          .handle = &hi2c1,
          .callback = NULL,
          .work_mode = IIC_BLOCK_MODE,
      },
      .id = 1, // 12 15损坏
      .work_mode = BMP280_NORMAL_MODE,
      .p_oversampling = BMP280_P_MODE_5,
      .t_oversampling = BMP280_T_MODE_5,
      .filter_coefficient = BMP280_FILTER_MODE_4,
      .t_sb = BMP280_T_SB1,
  };
  for (uint8_t i = 1; i <= 16; i++)
  {
    if (broken_sensors[i - 1]) // 跳过损坏的传感器,需要先一个一个查询
    {
      continue;
    }
    bmp280_conf.id = i; // 设置设备ID
    SwitchOn(bmp280_conf.id - 1);
    DWT_Delay(0.01);                                         // 延时，确保通道开启后再进行通信
    bmp280_instance[i - 1] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
    bmp280_measure[i - 1] = &bmp280_instance[i - 1]->measure; // 获取测量值指针
  }
  bmp280_conf.id = 1;
  bmp280_conf.iic_conf.dev_address = BMP280_ADDRESS + 1; // 设置设备地址
  SwitchOn(bmp280_conf.id - 1);
  DWT_Delay(0.01);                                      // 延时，确保通道开启后再进行通信
  bmp280_instance[16] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
  bmp280_measure[16] = &bmp280_instance[16]->measure;    // 获取测量值指针

  bmp280_conf.id = 9;
  bmp280_conf.iic_conf.dev_address = BMP280_ADDRESS + 1; // 设置设备地址
  SwitchOn(bmp280_conf.id - 1);
  DWT_Delay(0.01);                                      // 延时，确保通道开启后再进行通信
  bmp280_instance[17] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
  bmp280_measure[17] = &bmp280_instance[17]->measure;    // 获取测量值指针

  bmp280_conf.id = 10;
  bmp280_conf.iic_conf.dev_address = BMP280_ADDRESS + 1; // 设置设备地址
  SwitchOn(bmp280_conf.id - 1);
  DWT_Delay(0.01);                                      // 延时，确保通道开启后再进行通信
  bmp280_instance[18] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
  bmp280_measure[18] = &bmp280_instance[18]->measure;    // 获取测量值指针

  bmp280_conf.id = 11;
  bmp280_conf.iic_conf.dev_address = BMP280_ADDRESS + 1; // 设置设备地址
  SwitchOn(bmp280_conf.id - 1);
  DWT_Delay(0.01);                                      // 延时，确保通道开启后再进行通信
  bmp280_instance[19] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
  bmp280_measure[19] = &bmp280_instance[19]->measure;    // 获取测量值指针

#endif

#ifdef FINGER_MID

  CANComm_Init_Config_s cancomm_conf = {
      .can_config = {
          .can_handle = &hcan,
          .rx_id = 0x103,
          .tx_id = 0x104,
      },
      .send_data_len = sizeof(Cancomm_send_s),
      .recv_data_len = sizeof(Cancomm_recv_s),
  };
  can_comm_instance = CANCommInit(&cancomm_conf); // 初始化CAN通信实例

  BMP280Driver_conf_s bmp280_conf = {
      .iic_conf = {
          .dev_address = BMP280_ADDRESS,
          .handle = &hi2c1,
          .callback = NULL,
          .work_mode = IIC_BLOCK_MODE,
      },
      .id = 1, // 12 15损坏
      .work_mode = BMP280_NORMAL_MODE,
      .p_oversampling = BMP280_P_MODE_5,
      .t_oversampling = BMP280_T_MODE_5,
      .filter_coefficient = BMP280_FILTER_MODE_4,
      .t_sb = BMP280_T_SB1,
  };
  for (uint8_t i = 1; i <= 16; i++)
  {
    bmp280_conf.id = i; // 设置设备ID
    SwitchOn(bmp280_conf.id - 1);
    DWT_Delay(0.01);                                         // 延时，确保通道开启后再进行通信
    bmp280_instance[i - 1] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
    bmp280_measure[i - 1] = &bmp280_instance[i - 1]->measure; // 获取测量值指针
  }
#endif
#ifdef FINGER_DOWN
  CANComm_Init_Config_s cancomm_conf = {
      .can_config = {
          .can_handle = &hcan,
          .rx_id = 0x105,
          .tx_id = 0x106,
      },
      .send_data_len = sizeof(Cancomm_send_s),
      .recv_data_len = sizeof(Cancomm_recv_s),
  };
  can_comm_instance = CANCommInit(&cancomm_conf); // 初始化CAN通信实例
  BMP280Driver_conf_s bmp280_conf = {
      .iic_conf = {
          .dev_address = BMP280_ADDRESS,
          .handle = &hi2c1,
          .callback = NULL,
          .work_mode = IIC_BLOCK_MODE,
      },
      .id = 1, // 12 15损坏
      .work_mode = BMP280_NORMAL_MODE,
      .p_oversampling = BMP280_P_MODE_5,
      .t_oversampling = BMP280_T_MODE_5,
      .filter_coefficient = BMP280_FILTER_MODE_4,
      .t_sb = BMP280_T_SB1,
  };
  for (uint8_t i = 1; i <= 16; i++)
  {
    bmp280_conf.id = i; // 设置设备ID
    SwitchOn(bmp280_conf.id - 1);
    DWT_Delay(0.01);                                         // 延时，确保通道开启后再进行通信
    bmp280_instance[i - 1] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
    bmp280_measure[i - 1] = &bmp280_instance[i - 1]->measure; // 获取测量值指针
  }
#endif
#ifdef PALM
  CANComm_Init_Config_s cancomm_conf = {
      .can_config = {
          .can_handle = &hcan,
          .rx_id = 0x107,
          .tx_id = 0x108,
      },
      .send_data_len = sizeof(Cancomm_send_s),
      .recv_data_len = sizeof(Cancomm_recv_s),
  };
  can_comm_instance = CANCommInit(&cancomm_conf); // 初始化CAN通信实例
  BMP280Driver_conf_s bmp280_conf = {
      .iic_conf = {
          .dev_address = BMP280_ADDRESS,
          .handle = &hi2c1,
          .callback = NULL,
          .work_mode = IIC_BLOCK_MODE,
      },
      .id = 1, // 12 15损坏
      .work_mode = BMP280_NORMAL_MODE,
      .p_oversampling = BMP280_P_MODE_5,
      .t_oversampling = BMP280_T_MODE_5,
      .filter_coefficient = BMP280_FILTER_MODE_4,
      .t_sb = BMP280_T_SB1,
  };
  for (uint8_t i = 1; i <= 60; i++)
  {
    if (broken_sensors[i - 1])
    {
      continue; // 跳过损坏的传感器,需要先一个一个查询
    }
    bmp280_conf.id = i; // 设置设备ID
    SwitchOn(bmp280_conf.id - 1);
    DWT_Delay(0.01);                                          // 延时1ms
    bmp280_instance[i - 1] = BMP280Driver_Init(&bmp280_conf); // 初始化BMP280驱动实例
    bmp280_measure[i - 1] = &bmp280_instance[i - 1]->measure; // 获取测量值指针
  }
#endif

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
#ifdef FINGER_UP
    for (uint8_t i = 1; i <= 20; i++)
    {
      // if (bmp280_instance[i - 1].)
      // {
      //   continue; // 跳过损坏的传感器,需要先一个一个查询
      // }
      SwitchOn(bmp280_instance[i - 1]->id - 1);                                            // 打开对应的传感器
      DWT_Delay(0.0001);                                                                    // 延时，确保通道开启后再进行通信
      BMP280GetPressure(bmp280_instance[i - 1], &bmp280_measure[i - 1]->pressure);         // 获取气压值
      cancomm_send_data.pressure[i - 1] = float_to_uint8(bmp280_measure[i - 1]->pressure); // 将气压值存入发送数据结构体中
    }
    uint8_t tx_buf[sizeof(Cancomm_send_s)] = {0};               // 发送数据缓冲区
    memcpy(tx_buf, &cancomm_send_data, sizeof(Cancomm_send_s)); // 将发送数据结构体复制到发送数据缓冲区中
    CANCommSend(can_comm_instance, tx_buf);                     // 发送数据
    DWT_Delay(0.01);                                            // 延时1ms
#endif
#if defined FINGER_MID || defined FINGER_DOWN
    uint8_t tx_buf[16] = {0}; // 发送数据缓冲区
    for (uint8_t i = 1; i <= 16; i++)
    {
      // if (bmp280_instance[i - 1]->iic_instance->timeout_flag)
      // {
      //   cancomm_send_data.pressure[i - 1] = 0; // 将气压值设为0
      //   bmp280_measure[i - 1]->pressure = 0; // 将气压值设为0
      //   continue;                              // 跳过损坏的传感器,需要先一个一个查询
      // }
      SwitchOn(bmp280_instance[i - 1]->id - 1);                                            // 打开对应的传感器
      DWT_Delay(0.0001);                                                                    // 延时，确保通道开启后再进行通信
      BMP280GetPressure(bmp280_instance[i - 1], &bmp280_measure[i - 1]->pressure);         // 获取气压值
      cancomm_send_data.pressure[i - 1] = float_to_uint8(bmp280_measure[i - 1]->pressure); // 将气压值存入发送数据结构体中
    }
    memcpy(tx_buf, &cancomm_send_data, sizeof(Cancomm_send_s)); // 将发送数据结构体复制到发送数据缓冲区中
    CANCommSend(can_comm_instance, tx_buf);                     // 发送数据
    DWT_Delay(0.01);                                            // 延时1ms
#endif
    BMI088_Read(&BMI088);
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
